package com.primary.string;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author: yyh
 * @description: 字符串中的第一个唯一字符:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn5z8r/
 * @date: 2022/7/24 22:53
 */
public class FirstUniqChar {
    public static void main(String[] args) {
        System.out.println(firstUniqChar("leetcode"));
        System.out.println(firstUniqChar_1("leetcode"));
    }

    /**
     * 给定一个字符串 s ，找到 它的第一个不重复的字符，并返回它的索引 。如果不存在，则返回 -1 。
     */

    public static int firstUniqChar(String s) {
        byte[] bytes = s.getBytes();
        for (int i = 0; i < s.length(); i++) {
            if (s.indexOf(bytes[i]) == s.lastIndexOf(bytes[i])) {
                return i;
            }
        }
        return -1;
    }

    public static int firstUniqChar_1(String s) {
        Map<Byte, Integer> map = new LinkedHashMap<>(s.length());
        byte[] bytes = s.getBytes();
        for (int i = 0; i < s.length(); i++) {
            Integer num = map.get(bytes[i]);
            if (num == null) {
                num = 1;
            } else {
                num++;
            }
            map.put(bytes[i], num);
        }
        Byte b = null;
        Set<Map.Entry<Byte, Integer>> entries = map.entrySet();
        for (Map.Entry<Byte, Integer> entry : entries) {
            if (entry.getValue() == 1) {
                b = entry.getKey();
                break;
            }
        }
        if (b == null) {
            return -1;
        }
        return s.indexOf(b);
    }
}
